package com.fangwaii.core.authorization;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @author lxc18
 * @date 2024/12/6 15:31
 * @description GatewayAuthorizingRealm
 */
public class GatewayAuthorizingRealm extends AuthorizingRealm {
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof GatewayAuthenticationToken;
    }

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 暂时不需要做授权处理，所以直接返回null
        return null;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //对token进行解析
        String id = (String) authenticationToken.getPrincipal();
        String token = (String) authenticationToken.getCredentials();
        // 验证 Token
        if (id == null || !JWTUtil.verify(id, token)) {
            throw new AuthenticationException("Token 验证失败");
        }

        // 返回用户的认证信息
        return new SimpleAuthenticationInfo(id,token,getName());
    }
}
